<template>
    <view class="form">
        <view class="title">请填写以下信息（{{ type }}） </view>
        <u--form :model="form" ref="uForm">
            <u-form-item prop="content">
                <u--textarea v-model.trim="form.content" placeholder="请填写10字以上的描述以便我们理解" count :maxlength="100"
                    border="none"></u--textarea>
            </u-form-item>
            <view class="picture">
                <view class="label">
                    <text>图片证据</text>
                    <text>（选填）</text>
                </view>
                <u-upload :fileList="fileList" @delete="deletePic" useBeforeRead multiple :maxCount="1" maxSize="20971520"
                    accept="image" @afterRead="afterRead"></u-upload>
            </view>
            <u-form-item prop="phone" labelWidth="90">
                <view class="phone">
                    <text>
                        联系电话
                    </text>
                    <u--input v-model.trim="form.phone" placeholder="请输入手机号" border="none"></u--input>
                </view>
            </u-form-item>

            <view class="agreement-container" @click="radiovalue = !radiovalue">
                <label class="radio">
                    <radio :checked="radiovalue" color="#10bd0e" />
                </label>
                <text>同意商家及微信支付客服获取描述、图片证据和手机号码，以便联系你解决问题。并已阅读与同意
                    <text class="agreement" @click="goToAgreementPage('user')">用户协议</text>、
                    <text class="agreement" @click="goToAgreementPage('privacy')">隐私协议</text>、
                    <text class="agreement" @click="goToAgreementPage('children')">儿童保护协议</text>
                </text>
            </view>
        </u--form>
        <u-button text="提交" color="#5ac725" :customStyle="{ width: '660rpx', }" size="normal" @click="submit"></u-button>
        <u-toast ref="uToast"></u-toast>
    </view>
</template>

<script>
import { postFeedback } from '@/api/user'
export default {
    data() {
        return {
            type: '',
            // 表单
            form: {
                content: '',
                phone: null,
                img_url: '',
                type: 0,
                aid: null,
                eid: null
            },
            // 单选框
            radiovalue: false,
            // 表单校验
            rules: {
                // 字段名称
                phone: [
                    {
                        required: true,
                        message: '请填写手机号',
                        trigger: ['change', 'blur'],
                    },
                    {
                        pattern: /^(?:(?:\+|00)86)?1(?:(?:3[\d])|(?:4[5-79])|(?:5[0-35-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\d])|(?:9[1589]))\d{8}$/,
                        // 正则检验前先将值转为字符串
                        transform(value) {
                            return String(value);
                        },
                        message: '手机号码不正确',
                        // 触发器可以同时用blur和change
                        trigger: ['change', 'blur'],
                    }
                ],
                content: [
                    {
                        required: true,
                        message: '请描述您遇到的问题',
                        trigger: ['change', 'blur'],
                    },
                    {
                        min: 10,
                        max: 100,
                        message: '请填写10-100字符的问题描述',
                        // 触发器可以同时用blur和change
                        trigger: ['change', 'blur'],
                    }
                ]
            },
            fileList: []
        };
    },
    onLoad({ type }) {
        this.type = type
        switch (type) {
            case '功能异常':
                this.form.type = 1
                break;
            case '产品建议':
                this.form.type = 2
                break;
            case '交易投诉':
                this.form.type = 3
                break;
            default:
                break;
        }

    },
    created() {
        const { eid, aid } = uni.getStorageSync('userInfo')
        this.form.eid = eid
        this.form.aid = aid
    },
    methods: {
        // 1.新增图片
        async afterRead(event) {
            // 获取图片后缀
            const imageSuffix = event.file[0].url.substring(event.file[0].url.length - 3)
            // 检查文件类型
            if (imageSuffix !== 'jpg') {
                this.showToast({
                    type: 'warning',
                    message: "请检查图片类型是否为jpg",
                })
                return
            }

            // 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
            let lists = [].concat(event.file)
            let fileListLen = this[`fileList${event.name}`].length
            lists.map((item) => {
                this[`fileList${event.name}`].push({
                    ...item,
                    status: 'uploading',
                    message: '上传中'
                })
            })
            for (let i = 0; i < lists.length; i++) {
                const result = await this.uploadFile(lists[i].url)
                let item = this[`fileList${event.name}`][fileListLen]
                this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
                    status: 'success',
                    message: '',
                    url: result
                }))
                fileListLen++
            }
        },
        uploadFile(file) {

            return new Promise((resolve, reject) => {
                uni.uploadFile({
                    url: process.env.VUE_APP_BASE_URL + 'app.ximspace.com/Upload/Upload', // 仅为示例，非真实的接口地址
                    filePath: file,
                    name: 'file',
                    success: (res) => {
                        const data = JSON.parse(res.data).data
                        resolve(data.file_url)
                        this.form.img_url = data.file_url
                    }
                });
            })

        },
        // 2.删除图片
        deletePic(event) {
            this[`fileList${event.name}`].splice(event.index, 1)
        },
        // 3. 提示
        showToast(params) {
            this.$refs.uToast.show(params)
        },
        // 4. 提交表单
        async submit() {
            await this.$refs.uForm.validate()
            // 提示勾选
            if (!this.radiovalue) return this.showToast({
                type: 'warning',
                message: "请勾选同意协议",
            })
            //发送请求提交表单 
            const { code } = await postFeedback(this.form)
            code === 200 && uni.redirectTo({ url: '/pages_sub3/feedback/success' })

            uni.$u.toast('请检查是否填写完整~')

        },
        // 5. 跳转协议页面
        goToAgreementPage(url) {
            uni.navigateTo({ url: `/pages_sub2/agreement/${url}` })
        },


    },
    onReady() {
        // //如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则。
        this.$refs.uForm.setRules(this.rules)
    },
};
</script>
<style lang="scss" scoped>
.form {
    height: 100%;
    background-color: #f6f6f6;

    .title {
        height: 160rpx;
        padding: 60rpx 20rpx;
        box-sizing: border-box;
        font-size: 40rpx;

    }

    .picture {
        margin-top: 6rpx;
        padding: 30rpx 20rpx;
        color: #adadad;
        background-color: #fff;
        letter-spacing: 2px;
    }

    .phone {
        height: 120rpx;
        padding: 0rpx 20rpx;
        margin-top: 6rpx;
        background-color: #fff;
        display: flex;
        align-items: center;

        text:nth-child(1) {
            padding-right: 30rpx;
            font-size: 34rpx;
            font-weight: 700;
            letter-spacing: 2px;
        }
    }

    .agreement-container {
        height: 140rpx;
        padding: 30rpx;
        margin-bottom: 20rpx;
        display: flex;
        align-items: first baseline;
        font-size: 30rpx;
        color: #a1a1a1;



        .agreement {
            color: #67718c;
        }
    }

    .label {
        padding-right: 10rpx;
        margin-bottom: 30rpx;
        font-size: 34rpx;
        font-weight: 700;
        color: black;

        text:nth-child(2) {
            color: #bebebe;
            font-weight: lighter;
        }
    }


}
</style>